import { createStore } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import router, { asyncRoute, superRouter } from '@/router'
// console.log(router.getRoutes(), 'router')
export default createStore({
  state: {
    selectedMenuKey: '/introduct',
    roles: '',
    adminMenukey: '/nav'
  },
  mutations: {
    setSelectedMenuKey (state, key) {
      state.selectedMenuKey = key
    },
    setAdminMenukey (state, key) {
      state.adminMenukey = key
    },
    setUserRouter (state, roles) {
      state.roles = roles
      if (state.roles === 'superuser') {
        const totalRoute = [...asyncRoute, ...superRouter]
        totalRoute.forEach((item: any) => {
          const isAdded = router.getRoutes().some((route: any) => route.name === item.name)
          if (!isAdded) {
            router.addRoute('nav', item)
          }
        })
      } else {
        asyncRoute.forEach((item) => {
          const isAdded = router.getRoutes().some((route: any) => route.name === item.name)
          if (!isAdded) {
            router.addRoute('nav', item)
          }
        })
      }
    }
  },
  actions: {
    updateRouter (context, payload) {
      context.commit('setUserRouter', payload)
    }
  },
  modules: {
  },
  plugins: [createPersistedState({
    storage: window.sessionStorage
  })]
})
